<template>
  <div>
    <h1>巡检记录管理</h1>
    <!-- 显示/隐藏录入记录表单按钮 -->
    <el-button v-if="isInspector" @click="showRecordForm =!showRecordForm">
      {{ showRecordForm? '隐藏录入记录表单' : '录入记录' }}
    </el-button>
    <!-- 录入记录表单（巡检员专属） -->
    <el-form v-if="isInspector && showRecordForm" @submit.prevent="validateAndSubmitRecord" label-width="120px">
      <el-form-item label="任务ID">
        <el-select v-model="record.task_id" placeholder="请选择任务ID">
          <el-option v-for="taskId in taskIds" :key="taskId" :label="taskId" :value="taskId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态">
        <el-select v-model="record.device_status" placeholder="请选择设备状态">
          <el-option label="正常" value="正常"></el-option>
          <el-option label="异常" value="异常"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="异常描述" v-if="record.device_status === '异常'">
        <el-input v-model="record.abnormal_description" placeholder="请输入异常描述"></el-input>
      </el-form-item>
      <el-form-item label="完成时间">
        <el-input v-model="record.completion_time" readonly></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="validateAndSubmitRecord">提交记录</el-button>
      </el-form-item>
    </el-form>
    <!-- 显示/隐藏查询表单按钮 -->
    <el-button @click="showQueryForm =!showQueryForm">
      {{ showQueryForm? '隐藏查询表单' : '查询记录' }}
    </el-button>
    <!-- 巡检记录查询表单 -->
    <div v-if="showQueryForm" class="center-form">
      <el-form @submit.prevent="fetchRecords" label-width="120px">
        <el-form-item label="记录ID">
          <el-input v-model="queryParams.record_id" placeholder="请输入记录ID" style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item label="设备ID">
          <el-input v-model="queryParams.device_id" placeholder="请输入设备ID" style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
              v-model="queryParams.start_time"
              type="datetime"
              placeholder="请选择开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
              v-model="queryParams.end_time"
              type="datetime"
              placeholder="请选择结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchRecords">查询记录</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 记录列表展示 -->
    <el-table :data="records" stripe>
      <el-table-column prop="id" label="记录ID"></el-table-column>
      <el-table-column prop="task_id" label="任务ID"></el-table-column>
      <el-table-column prop="device_status" label="设备状态"></el-table-column>
      <el-table-column prop="completion_time" label="完成时间">
        <template #default="{ row }">
          {{ formatTime(row.completion_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="text" @click="fetchRecordDetails(row.id)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 记录详情展示 -->
    <el-dialog v:visible.sync="dialogVisible" title="记录详情">
      <template #content>
        <p>记录ID: {{ singleRecord.id }}</p>
        <p>任务ID: {{ singleRecord.task_id }}</p>
        <p>设备状态: {{ singleRecord.device_status }}</p>
        <p v-if="singleRecord.abnormal_description">异常描述: {{ singleRecord.abnormal_description }}</p>
        <p>完成时间: {{ formatTime(singleRecord.completion_time) }}</p>
      </template>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭详情</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      record: {
        task_id: '',
        device_status: '正常',
        abnormal_description: '',
        completion_time: ''
      },
      records: [],
      taskIds: [],
      queryParams: {
        record_id: '',
        device_id: '',
        start_time: '',
        end_time: ''
      },
      singleRecord: null,
      // 假设从后端获取用户角色判断是否为巡检员
      isInspector: false,
      dialogVisible: false,
      showRecordForm: false,
      showQueryForm: false
    };
  },
  created() {
    const userRole = localStorage.getItem('role');
    if (userRole === '巡检员') {
      this.isInspector = true;
    }
    this.fetchTaskIds();
  },
  methods: {
    async fetchTaskIds() {
      try {
        const response = await axios.get('/api/tasks');
        if (response.status === 200) {
          this.taskIds = response.data.map(task => task.id);
        }
      } catch (error) {
        console.error('获取任务ID列表失败', error);
      }
    },
    async validateAndSubmitRecord() {
      if (!this.record.task_id) {
        console.error('请选择任务ID');
        return;
      }
      if (this.record.device_status === '异常' &&!this.record.abnormal_description) {
        console.error('请输入异常描述');
        return;
      }
      this.record.completion_time = new Date().getTime();
      try {
        const response = await axios.post('/api/records', this.record);
        if (response.status === 200) {
          await this.fetchRecords();
          this.record = {
            task_id: '',
            device_status: '正常',
            abnormal_description: '',
            completion_time: ''
          };
        }
      } catch (error) {
        console.error('提交巡检记录失败', error);
      }
    },
    async fetchRecords() {
      try {
        const response = await axios.get('/api/records', {
          params: this.queryParams
        });
        if (response.status === 200) {
          this.records = response.data;
        }
      } catch (error) {
        console.error('查询巡检记录列表失败', error);
      }
    },
    async fetchRecordDetails(id) {
      try {
        const response = await axios.get(`/api/records/${id}`);
        if (response.status === 200) {
          this.singleRecord = response.data;
          this.dialogVisible = true;
        }
      } catch (error) {
        console.error('获取单条记录详情失败', error);
      }
    },
    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleString();
    }
  }
};
</script>

<style scoped>
.center-form {
  display: flex;
  justify-content: center;
}
</style>